using DeviceCommons.DeviceMessages.Factories;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.DeviceMessages.Enums;

namespace DeviceCommons.DeviceMessages.Builders
{
    /// <summary>
    /// 增强的设备消息构建器
    /// 能够自动根据设备类型的状态配置来创建状态
    /// </summary>
    public class EnhancedDeviceMessageBuilder : DeviceMessageBuilder
    {
        private byte _currentDeviceType;

        /// <summary>
        /// 重写WithMainDevice方法以记录设备类型
        /// </summary>
        public new EnhancedDeviceMessageBuilder WithMainDevice(string did, byte deviceType)
        {
            _currentDeviceType = deviceType;
            base.WithMainDevice(did, deviceType);
            return this;
        }

        /// <summary>
        /// 重写WithMainDevice方法以记录设备类型
        /// </summary>
        public new EnhancedDeviceMessageBuilder WithMainDevice(string did, byte deviceType, Action<DeviceInfoBuilder> config)
        {
            _currentDeviceType = deviceType;
            base.WithMainDevice(did, deviceType, config);
            return this;
        }

        /// <summary>
        /// 使用设备状态配置添加读数
        /// </summary>
        /// <param name="timeOffset">时间偏移</param>
        /// <param name="stateValues">状态值元组数组：(sid, value)</param>
        /// <returns>构建器实例</returns>
        public EnhancedDeviceMessageBuilder AddReadingWithConfiguration(short timeOffset, params (byte sid, object value)[] stateValues)
        {
            // 获取设备状态配置
            var configuration = DeviceStateConfigurationRegistry.GetConfiguration(_currentDeviceType);
            if (configuration == null)
            {
                throw new InvalidOperationException($"设备类型 {_currentDeviceType} 没有注册状态配置");
            }

            // 验证状态完整性
            var providedSids = stateValues.Select(sv => sv.sid);
            var (isValid, missingStates) = configuration.ValidateStateCompleteness(providedSids);
            
            if (!isValid)
            {
                var missingStatesList = string.Join(", ", missingStates);
                throw new InvalidOperationException($"设备类型 {_currentDeviceType} 缺少必需的状态: {missingStatesList}");
            }

            // 使用配置创建状态
            var factory = DeviceStateConfigurationRegistry.GetFactory(_currentDeviceType);
            if (factory is ConfigurableStateFactory configurableFactory)
            {
                var states = configurableFactory.CreateStatesFromValues(stateValues);
                
                // 使用基类的方法添加读数
                AddReading(timeOffset, reading =>
                {
                    foreach (var state in states.StateArray)
                    {
                        reading.AddState(state.SID, state.ValueText, state.ValueType);
                    }
                });
            }
            else
            {
                // 回退到默认实现
                AddReading(timeOffset, stateValues.Select(sv => (sv.sid, sv.value, (StateValueTypeEnum?)null)).ToArray());
            }

            return this;
        }

        /// <summary>
        /// 使用设备状态配置添加读数（使用字典）
        /// </summary>
        /// <param name="timeOffset">时间偏移</param>
        /// <param name="stateValues">状态值字典</param>
        /// <returns>构建器实例</returns>
        public EnhancedDeviceMessageBuilder AddReadingWithConfiguration(short timeOffset, Dictionary<byte, object> stateValues)
        {
            var stateValuesArray = stateValues.Select(kv => (kv.Key, kv.Value)).ToArray();
            return AddReadingWithConfiguration(timeOffset, stateValuesArray);
        }

        /// <summary>
        /// 使用设备状态配置添加读数（自动填充默认值）
        /// </summary>
        /// <param name="timeOffset">时间偏移</param>
        /// <param name="stateValues">状态值元组数组：(sid, value)，可选值</param>
        /// <returns>构建器实例</returns>
        public EnhancedDeviceMessageBuilder AddReadingWithDefaults(short timeOffset, params (byte sid, object value)[] stateValues)
        {
            var configuration = DeviceStateConfigurationRegistry.GetConfiguration(_currentDeviceType);
            if (configuration == null)
            {
                throw new InvalidOperationException($"设备类型 {_currentDeviceType} 没有注册状态配置");
            }

            // 创建包含所有必需状态的状态集合
            var factory = DeviceStateConfigurationRegistry.GetFactory(_currentDeviceType);
            if (factory is ConfigurableStateFactory configurableFactory)
            {
                var states = configurableFactory.CreateStatesFromValues(stateValues);
                
                AddReading(timeOffset, reading =>
                {
                    foreach (var state in states.StateArray)
                    {
                        reading.AddState(state.SID, state.ValueText, state.ValueType);
                    }
                });
            }

            return this;
        }

        /// <summary>
        /// 验证设备类型是否已注册状态配置
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>是否已注册</returns>
        public static bool IsDeviceTypeConfigured(byte deviceType)
        {
            return DeviceStateConfigurationRegistry.IsRegistered(deviceType);
        }

        /// <summary>
        /// 获取设备类型的状态配置信息
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>状态配置信息</returns>
        public static IDeviceStateConfiguration? GetDeviceConfiguration(byte deviceType)
        {
            return DeviceStateConfigurationRegistry.GetConfiguration(deviceType);
        }
    }
}
